package com.cloudcc.mobile.view.im;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.adapter.ViewHolder;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.CoworkerListAdapter;
import com.cloudcc.mobile.entity.CoworkerEntity;
import com.cloudcc.mobile.event.CoworkerEventList.CoworkerListEvent;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.util.PinyinUtils;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.util.UserUtils;
import com.cloudcc.mobile.view.main.fragment.CoworkerListFragment;
import com.cloudcc.mobile.weight.SideBar;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.Bind;

import static com.cloudcc.cloudframe.CApplication.position;
import static com.cloudcc.mobile.R.id.expandablelist;

/**
 * @Description: 群组选择联系人
 * @author wangzhiqiang
 * @date 2016-1-14 下午1:53:35
 * 
 */
public class GroupPickFragment extends CoworkerListFragment {
	private String mEns = RunTimeManager.getInstance().getlanguage();
	/** 是否为一个新建的群组 */
	protected boolean isCreatingNewGroup;
	/** 是否为单选 */
	private boolean isSignleChecked;
	/** group中一开始就有的成员 */
	private List<String> exitingMembers;
	private String groupName;
	private String groupId;
	private Button leftbutton;
	private TextView centertv;
	private TextView righttv;
	private Button left_image;
	private MySubListAdapter mAdapter;
    @Bind(R.id.cower_sidrbar)
    SideBar sideBar;
	private List<CoworkerEntity> sortdata;
	@Override
	public void init() {
		super.init();
		leftbutton = (Button) findViewById(R.id.allbtn);
		leftbutton.setVisibility(View.GONE);
		left_image = (Button) findViewById(R.id.left_image111);
		left_image.setVisibility(View.VISIBLE);
		// leftbutton.setText("");
		// leftbutton.setBackgroundResource(R.drawable.em_mm_title_back);
		centertv = (TextView) findViewById(R.id.bar_title_text);
		righttv = (TextView) findViewById(R.id.groupTextView);
		String mEns = RunTimeManager.getInstance().getlanguage();
		if ("en".equals(mEns)) {
			righttv.setText("Save");
			centertv.setText("Colleague");
		}else{
			righttv.setText("确定");
			centertv.setText("选择同事");
		}
		righttv.setTextColor(Color.WHITE);
		righttv.setVisibility(View.VISIBLE);
		righttv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				save();
			}
		});
		left_image.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				getActivity().finish();
			}
		});
		initArg();

		if (groupId == null) {// 创建群组
			isCreatingNewGroup = true;
		} else {
			// 获取此群组的成员列表
			EMGroup group = EMGroupManager.getInstance().getGroup(groupId);
			exitingMembers = group.getMembers();
		}
		// [005201576751721ufptn2010000000050855wyhh,
		// 005201511668834zvq432010000000050855wyhh,
		// 00520159411661123fi62010000000050855wyhh,
		// 005201570227360lsuhv2010000000050855wyhh]
		// 005201301193416acljg2010000000050855wyhh
		// 005201511668834zvq432010000000050855wyhh
		if (exitingMembers == null)
			exitingMembers = new ArrayList<String>();
		mLoadMoreLayout.setEnabled(false);
		// headerbar.setLeftImageResource(R.drawable.ease_mm_title_back);
		// headerbar.setTitle("请选择联系人");
		// headerbar.setRightText("保存");

        // 设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @SuppressLint("NewApi")
            @Override
            public void onTouchingLetterChanged(String s) {


                int position = mAdapter.getPositionForSection(s.charAt(0));
                if(position != -1){
                    mListView.setSelection(position);
                }
            }
        });
	}

	private void initArg() {
		Bundle bundle = getArguments();
		if (bundle != null) {
			groupName = bundle.getString("groupName");
			groupId = bundle.getString("groupId");
		}
	}

	public void onEventMainThread(CoworkerListEvent event) {
		headerbar.completeProgress();
		mRefreshLayout.refreshComplete();
		if (event.isError()) {
			Toast.makeText(mContext, event.getMessage(), 0).show();
			return;
		}
		refreshData(event.getData());
	}

	protected void refreshData(List<CoworkerEntity> data) {

		try {
			NameComParatorc sortName = new NameComParatorc();
			sortdata = data;
			Collections.sort(sortdata, sortName);

		} catch (Exception e) {
			e.printStackTrace();
		}
		if (mAdapter == null) {
			mAdapter = new MySubListAdapter(mContext);
			mListView.setAdapter(mAdapter);
		}
		if (isFromRefresh()) {
			mContactes.clear();
			mContactes.addAll(sortdata);
			mAdapter.changeData(sortdata);
		} else {
			mContactes.addAll(sortdata);
			mAdapter.addData(sortdata);
		}
	}
	private class NameComParatorc implements Comparator<CoworkerEntity> {
		@Override
		public int compare(CoworkerEntity lhs, CoworkerEntity rhs) {

			String str1 = PinyinUtils.converterToFirstSpell((rhs.getName().substring(0,1)));
			String str2 = PinyinUtils.converterToFirstSpell((lhs.getName().substring(0,1)));
			return str2.compareTo(str1);
		}
	}
	private List<String> checkIds = new ArrayList<String>();

	private class MySubListAdapter extends CoworkerListAdapter {

		public List<String> getToBeAddMembers() {
			return checkIds;
		}

		public MySubListAdapter(Context mContext) {
			super(mContext);
		}

		@Override
		public void convert(ViewHolder holder, CoworkerEntity t) {
            final int postion = holder.getPostion();
			ImageView ivLogo = holder.getView(R.id.contact_item_name);
			String uri = UrlTools.getTopImage(t.getId());
			int colorindex = holder.getPostion() % colors.length;
			UserUtils.setLogoRound(uri, ivLogo, colors[colorindex],
					t.getNickRowName(), mContext);
			holder.setText(R.id.contact_item_logo, t.getName());
			CheckBox cbCheckBox = holder.getView(R.id.checkbox);
			if (hasInExit(t.getHxusername())) {
				cbCheckBox
						.setButtonDrawable(R.drawable.em_checkbox_bg_selector);
				cbCheckBox.setOnCheckedChangeListener(null);
				cbCheckBox.setChecked(true);
			} else {
				cbCheckBox
						.setButtonDrawable(R.drawable.em_checkbox_bg_selector);
				cbCheckBox.setOnCheckedChangeListener(null);
				cbCheckBox.setChecked(false);

				if (hasInChecked(t.getHxusername())) {
					cbCheckBox.setChecked(true);
				} else {
					cbCheckBox.setChecked(false);
				}
				final String userHxName = t.getHxusername();
				final String mIds = t.getId();
				final CheckBox ch = cbCheckBox;
				cbCheckBox
						.setOnCheckedChangeListener(new OnCheckedChangeListener() {
							@Override
							public void onCheckedChanged(
									CompoundButton buttonView, boolean isChecked) {
								if (RunTimeManager.getInstance().getUserId().equals(mIds)) {
								
										ch.setClickable(false);
										ch.setChecked(false);
										if ("en".equals(mEns)) {
											Toast.makeText(mContext, "Sorry, you can not add yourself", 1).show();
										}else{
											Toast.makeText(mContext, "对不起，不能添加自己", 1).show();
									}
								
									return;
								}
							
								if (hasInChecked(userHxName)) {
									checkIds.remove(userHxName);
								} else {
									checkIds.add(userHxName);
								}
							}
						});

            }
			if(hasCheck(t.getHxusername())){
				cbCheckBox.setEnabled(false);
			}else {
				cbCheckBox.setEnabled(true);
			}

            //根据position获取分类的首字母的char ascii值
            int section = getSectionForPosition(t);

            //如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
            if(postion == getPositionForSection(section)){
                holder.setVisibility(R.id.llbigA,View.VISIBLE);
                holder.setText(R.id.bigA,PinyinUtils.cn2FirstSpellx(mData.get(postion).getName()).toUpperCase().substring(0,1));
//                    viewHolder.tvLetter.setVisibility(View.VISIBLE);
//                    viewHolder.tvLette r.setText(mContent.getSortLetters());
            }else{
//                    viewHolder.tvLetter.setVisibility(View.GONE);
                holder.setVisibility(R.id.llbigA,View.GONE);
            }
		}

		private boolean hasInExit(String username) {
			for (String exiting : exitingMembers) {
				if (StringUtils.equals(username.trim(), exiting)) {
					return true;
				}
			}
			return false;
		}

		private boolean hasCheck(String username) {
			try {
				if (StringUtils.equals(username.trim(), exitingMembers.get(0))) {
					return true;
				}else{
					return false;
				}
			}catch (Exception ex){
				return false;
			}

		}
        /**
         * 根据ListView的当前位置获取分类的首字母的char ascii值
         */
        public int getSectionForPosition(CoworkerEntity t) {
            return PinyinUtils.cn2FirstSpellx(t.getName()).toUpperCase().charAt(0);
        }
        /**
         * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
         */
        public int getPositionForSection(int section) {
            for (int i = 0; i < getCount(); i++) {
				if(mData.get(i).getName()!=null) {
					String sortStr = PinyinUtils.cn2FirstSpellx(mData.get(i).getName());

					char firstChar = sortStr.toUpperCase().charAt(0);
					if (firstChar == section) {
						return i;
					}
				}

            }

            return -1;
        }
//        @Override
//        public Object[] getSections() {
//            return null;
//        }

        private boolean hasInChecked(String userName) {
			StringBuilder sb = new StringBuilder();
			sb.append("当前人员：");
			for (String username : checkIds) {
				sb.append(username);
				sb.append("#");
			}
			System.out.println(sb.toString());
			return checkIds.contains(userName);
		}

		@Override
		public int getLayoutId() {
			return R.layout.contact_list_select;
		}

	}

	/**
	 * 确认选择的members
	 * 
	 * @param v
	 */
	public void save(View v) {
		LogUtils.d("imchat", "新增成员个数:" + checkIds.size());
		getActivity().setResult(
				Activity.RESULT_OK,
				new Intent().putExtra("newmembers",
						((MySubListAdapter) mAdapter).getToBeAddMembers()
								.toArray(new String[0])));
		getActivity().finish();
	}

	public void save() {
		LogUtils.d("imchat", "新增成员个数:" + checkIds.size());
		getActivity().setResult(
				Activity.RESULT_OK,
				new Intent().putExtra("newmembers",
						((MySubListAdapter) mAdapter).getToBeAddMembers()
								.toArray(new String[0])));
		getActivity().finish();
	}

	@Override
	public void onClickRight(View v) {
		save(v);
	}

	@Override
	public void onClickLeft(View v) {
		getActivity().finish();
	}

}
